# -*- coding: utf-8 -*-
# @Time    : 2025/6/12 0:29
# @Author  : wsxzy98@outlook.com
# @File    : package_edit_wizard.py
# @Software: VScode

from odoo import models, fields, api
from odoo.exceptions import UserError

class PackageEditWizard(models.TransientModel):
    _name = 'package.edit.wizard'
    x_line_ids = fields.One2many('x.package.line.wizard', 'wizard_id', string='明细内容')
    location_id = fields.Many2one('stock.location', string='库位', required=True)

    @api.model
    def default_get(self, fields):
        res = super().default_get(fields)
        package_id = self.env.context.get('active_id')
        package = self.env['stock.quant.package'].browse(package_id)
        lines = []
        for quant in package.quant_ids:
            lines.append((0, 0, {
                'product_id': quant.product_id.id,
                'lot_id': quant.lot_id.id if quant.lot_id else False,
                'quantity': quant.quantity,
                'origin_name': quant.origin_name or (quant.product_id.product_tmpl_id.origin if quant.product_id else ''),
                'customer_reference': quant.customer_reference or '',  # 读取客户参考号
            }))
        res['x_line_ids'] = lines
        res['location_id'] = package.location_id.id if package.location_id else False
        return res

    def action_save_lines(self):
        self.ensure_one()
        location = self.location_id
        if not location:
            raise UserError('请先选择一个库位后再保存！')
        package = self.env['stock.quant.package'].browse(self.env.context.get('active_id'))
        if package.x_lock_state != 'unlocked':
            raise UserError('包裹已锁定，无法保存内容，请先拆包！')

        Quant = self.env['stock.quant']
        # 1. 原有quant表：key = (product_id, lot_id, customer_reference)
        old_quants = {}
        for q in package.quant_ids:
            key = (q.product_id.id, q.lot_id.id if q.lot_id else False, q.customer_reference or '')
            old_quants[key] = q

        # 2. 新表单行：key = (product_id, lot_id, customer_reference)
        new_lines = {}
        for l in self.x_line_ids:
            key = (l.product_id.id, l.lot_id.id if l.lot_id else False, l.customer_reference or '')
            new_lines[key] = l

        # 3. 先处理被删除的（原有有，表单没了）=> 删除
        for key, q in old_quants.items():
            if key not in new_lines:
                q.unlink()

        # 4. 处理数量变化的（原有有，表单有，数量不一样）=> 更新
        for key, l in new_lines.items():
            if key in old_quants:
                q = old_quants[key]
                if q.quantity != l.quantity or q.origin_name != (l.origin_name or ''):
                    q.write({
                        'quantity': l.quantity,
                        'origin_name': l.origin_name or ''
                    })
                    # 同步原产地
                    if l.origin_name and l.product_id:
                        tmpl = l.product_id.product_tmpl_id
                        if tmpl.origin != l.origin_name:
                            tmpl.origin = l.origin_name
            else:
                # 5. 新增的（表单有，原有没有）=> 新建
                Quant.create({
                    'package_id': package.id,
                    'product_id': l.product_id.id,
                    'lot_id': l.lot_id.id if l.lot_id else False,
                    'quantity': l.quantity,
                    'location_id': location.id,
                    'company_id': package.company_id.id,
                    'origin_name': l.origin_name or '',
                    'customer_reference': l.customer_reference or '',
                })
                # 同步原产地
                if l.origin_name and l.product_id:
                    tmpl = l.product_id.product_tmpl_id
                    if tmpl.origin != l.origin_name:
                        tmpl.origin = l.origin_name
        return {'type': 'ir.actions.act_window_close'}

class XPackageLineWizard(models.TransientModel):
    _name = 'x.package.line.wizard'
    wizard_id = fields.Many2one('package.edit.wizard', string='向导')
    product_id = fields.Many2one('product.product', string='产品', required=True)
    lot_id = fields.Many2one('stock.lot', string='批次/序列号')
    quantity = fields.Float('数量', required=True)
    origin_name = fields.Char('原产地')
    customer_reference = fields.Char('客户参考号')  # 新增

    @api.onchange('product_id')
    def _onchange_product_id_origin_name(self):
        if self.product_id:
            self.origin_name = self.product_id.product_tmpl_id.origin
